﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;

namespace CalmNine.Framework
{
    public class AudioKit
    {
        public AudioGroup Music => mGroups[GroupType.Music];
        public AudioGroup Sound => mGroups[GroupType.Sound];
        public AudioGroup Voice => mGroups[GroupType.Voice];

        public AudioParam DefaultMusicParam => Music.Setting.Param.Default();
        public AudioParam DefaultSoundParam => Sound.Setting.Param.Default();
        public AudioParam DefaultVoiceParam => Voice.Setting.Param.Default();

        public Transform root;

        private Dictionary<GroupType, AudioGroup> mGroups;
        private AudioKit() {
            var kit = new GameObject("AudioKit");
            kit.AddComponent<AudioListener>();
            UnityEngine.Object.DontDestroyOnLoad(kit);
            this.root = kit.transform;
            AudioMixer mixer = Resources.Load<AudioMixer>("AudioKit/Config/Mixer");
            var groupSetting = Resources.Load<AudioSettingAsset>("AudioKit/Config/AudioSetting").Groups;
            mGroups = new Dictionary<GroupType, AudioGroup>();
            var defaultAudioLoder = new DefaultAudioLoder();
            foreach (var setting in groupSetting)
            {
                AudioMixerGroup groupMixer = GetMixGroup(mixer, setting.Type.ToString());
                AudioGroup groupAgent = new AudioGroup(defaultAudioLoder, setting, root, groupMixer);
                mGroups.Add(setting.Type, groupAgent);
            }
            // 播放人声暂停其他声音静音
            Voice.SetOnPlay(() =>
            {
                Music.TempVolume(0.2f);
                Sound.TempVolume(0.2f);
            });
            // 恢复背景音乐和音效
            Voice.SetOnIdle(() =>
            {
                Music.TempVolume(Music.Volume);
                Sound.TempVolume(Sound.Volume);
            });
        }
        public static AudioKit Global = new AudioKit();

        /// <summary>
        /// 自定义音频加载方法
        /// </summary>
        /// <param name="loder"></param>
        public void SetAudioLoder(IAudioLoader loder) 
        {
            foreach (var group in mGroups.Values)
            {
                group.AudioLoder = loder;
            }
        }

        AudioMixerGroup GetMixGroup(AudioMixer mixer, string groupName)
        {
            AudioMixerGroup[] audioMixerGroups = mixer.FindMatchingGroups("Master/" + groupName);

            if (audioMixerGroups.Length > 0)
            {
                return audioMixerGroups[0];
            }
            else
            {
                throw new Exception("必须创建对应的mixergroup");
            }
        }

        public void StopAll() 
        {
            Music.StopAll();
            Sound.StopAll();
            Voice.StopAll();
        }
    }
}
